package com.etonenet.controller.system;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.etonenet.entity.system.SysLog;
import com.etonenet.entity.system.SystemNode;
import com.etonenet.entity.system.security.Role;
import com.etonenet.entity.system.security.UserBs;
import com.etonenet.enums.syslog.OperType;
import com.etonenet.enums.systemnode.SystemNodeType;
import com.etonenet.repository.system.security.RoleUserRepository;
import com.etonenet.repository.system.security.UserBsRepository;
import com.etonenet.service.system.MenuService;
import com.etonenet.service.system.RoleService;
import com.etonenet.service.system.SysLogService;
import com.etonenet.service.system.UserBsService;
import com.etonenet.taglibs.component.AjaxPage;
import com.etonenet.taglibs.util.AjaxPageUtil;
import com.etonenet.util.AutocompleteUtil;
import com.etonenet.util.DateUtil;
import com.etonenet.util.StringUtil;
import com.etonenet.util.TilesUtil;
import com.etonenet.web.Autocomplete;
import com.etonenet.web.PageRequest;
import com.etonenet.web.SpecificationCondition;
import com.etonenet.web.SpecificationHelper;
import com.etonenet.web.UrlConstants;

import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * @author wxu
 *
 */
@ApiIgnore
@Controller
public class SystemController {

	@Resource
	private MenuService menuService;

	@Resource
	private SysLogService sysLogService;

	@Resource
	private RoleService roleService;

	@Resource
	private RoleUserRepository roleUserEm;

	@Resource
	private UserBsRepository userBsEm;

	@Resource
	private UserBsService userBsService;

	@RequestMapping(UrlConstants.SYSTEM_AUTH_INDEX)
	public ModelAndView sysAuthIndex() {

		ModelAndView mv = new ModelAndView(TilesUtil.getPath(UrlConstants.SYSTEM_AUTH_INDEX));
		return mv;
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_AUTH_DATA)
	public AjaxPage sysAuthData(Integer pageNumber, Integer pageSize, String displayName, String sortName,
			String sortOrder) {

		List<SpecificationCondition> conditions = new ArrayList<>();
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("displayName", displayName));

		SpecificationHelper<Role> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);

		Page<?> p = roleService.page(new PageRequest(pageNumber, pageSize), sh.createSpecification());
		return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_AUTH_SAVE)
	public String sysAuthData(Long roleid, String... data) {

		List<Long> userIds = new ArrayList<>();
		for (String id : data) {
			if (StringUtil.isNotEmpty(id))
				userIds.add(Long.valueOf(id));
		}

		userBsService.saveRoleUsers(roleid, userIds);
		return "保存成功";
	}

	@RequestMapping(UrlConstants.SYSTEM_AUTH_ROLEUSER)
	public ModelAndView sysAuthRoleUser(Long roleid) {

		ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_AUTH_ROLEUSER);

		List<UserBs> roleUsers = userBsEm.listUsersByRoleId(roleid);
		List<UserBs> noroleUsers = new ArrayList<>();

		for (UserBs u : userBsEm.listAllUser())
			if (!roleUsers.contains(u))
				noroleUsers.add(u);

		mv.addObject("noroleUsers", noroleUsers);
		mv.addObject("roleUsers", roleUsers);
		mv.addObject("roleid", roleid);

		return mv;
	}

	@RequestMapping(UrlConstants.SYSTEM_ROLE_INDEX)
	public ModelAndView sysRoleIndex() {

		ModelAndView mv = new ModelAndView(TilesUtil.getPath(UrlConstants.SYSTEM_ROLE_INDEX));
		return mv;
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_DATA)
	public AjaxPage sysRoleData(Integer pageNumber, Integer pageSize, String displayName, String sortName,
			String sortOrder) {

		List<SpecificationCondition> conditions = new ArrayList<>();
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("displayName", displayName));

		SpecificationHelper<Role> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);

		Page<?> p = roleService.page(new PageRequest(pageNumber, pageSize), sh.createSpecification());
		return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_NEW)
	public ModelAndView sysRoleNew() {
		ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_ROLE_NEW);

		return mv;
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_VIEW)
	public ModelAndView sysRoleView(Long roleId) {
		ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_ROLE_VIEW);
		mv.addObject("role", roleService.findOne(roleId));

		return mv;
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_UPDATE)
	public String sysRoleUpdate(Role role) {
		roleService.update(role);

		return "修改成功";
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_CREATE)
	public String sysRoleCreate(Role role) {
		roleService.create(role);

		return "保存成功";
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_ROLE_DEL)
	public String sysRoleDel(@RequestBody List<Role> data) {
		roleService.del(data);

		return "删除成功";
	}

	@RequestMapping(UrlConstants.SYSTEM_LOG_INDEX)
	public ModelAndView sysLogIndex() {

		ModelAndView mv = new ModelAndView(TilesUtil.getPath(UrlConstants.SYSTEM_LOG_INDEX));
		mv.addObject("operType", OperType.toDisplayMap());

		return mv;
	}

	@ResponseBody
	@RequestMapping(UrlConstants.SYSTEM_LOG_DATA)
	public AjaxPage sysLogData(Integer pageNumber, Integer pageSize, SysLog search, String operUserStr,
			String timeStart, String timeEnd, String sortName, String sortOrder) throws ParseException {

		List<SpecificationCondition> conditions = new ArrayList<>();
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("classId", search.getClassId()));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("className", search.getClassName()));
		if (StringUtil.isNotEmpty(operUserStr))
			conditions.add(SpecificationCondition.eq("operUser.userId", operUserStr.split("-")[0]));
		conditions.add(SpecificationCondition.eq("oper", search.getOper()));
		conditions.add(SpecificationCondition.equalOrLikeIgnoreCase("prop", search.getProp()));
		if (StringUtil.isNotEmpty(timeStart) || StringUtil.isNotEmpty(timeEnd)) {
			Date start = new Date(0);
			Date end = new Date();
			if (StringUtil.isNotEmpty(timeStart))
				start = DateUtil.parseDate(timeStart, "yyyy-MM-dd");
			if (StringUtil.isNotEmpty(timeEnd))
				end = DateUtil.parseDate(timeEnd, "yyyy-MM-dd");
			conditions.add(SpecificationCondition.between("logTime", start, end));
		}

		if (StringUtil.isEmpty(sortName)) {
			sortOrder = "desc";
			sortName = "logTime";
		}

		SpecificationHelper<SysLog> sh = new SpecificationHelper<>(conditions, sortOrder, sortName);

		Page<?> p = sysLogService.page(new PageRequest(pageNumber, pageSize), sh.createSpecification());
		return AjaxPageUtil.toAjaxPage(p.getTotalElements(), p.getContent());
	}

	@RequestMapping(UrlConstants.SYSTEM_LOG_AUTOCOMPLETE_OPERUSER)
	@ResponseBody
	public List<Autocomplete> autoOperUser(String term) {

		return AutocompleteUtil.object2auto(userBsEm.auto(term));
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_INDEX)
	public ModelAndView nodeIndex() {

		ModelAndView mv = new ModelAndView(TilesUtil.getPath(UrlConstants.SYSTEM_NODE_INDEX));
		mv.addObject("nodetree", menuService.listTreegrid());

		return mv;
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_NEW)
	public ModelAndView nodeNew(String parentid) {

		ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_NODE_NEW);
		mv.addObject("parentid", parentid);
		mv.addObject("systemNodeType", SystemNodeType.toDisplayMap());
		return mv;
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_VIEW)
	public ModelAndView nodeView(Long nodeid) {

		ModelAndView mv = new ModelAndView(UrlConstants.SYSTEM_NODE_VIEW);
		mv.addObject("node", menuService.findByNodeId(nodeid));
		mv.addObject("systemNodeType", SystemNodeType.toDisplayMap());
		return mv;
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_CREATE)
	@ResponseBody
	public String nodeCreate(SystemNode node, String nname, Integer ntype, String parenid) {

		node.setNodeName(nname);
		node.setNodeType(ntype);
		if (StringUtil.isNotEmpty(parenid)) {

			SystemNode parent = menuService.findByNodeId(Long.valueOf(parenid));
			if (parent != null)
				node.setParent(parent);
		}
		menuService.save(node);
		return "创建成功";
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_UPDATE)
	@ResponseBody
	public String nodeUpdate(SystemNode node, String nname, Integer ntype) {

		node.setNodeName(nname);
		node.setNodeType(ntype);
		menuService.update(node);
		return "修改成功";
	}

	@RequestMapping(UrlConstants.SYSTEM_NODE_DEL)
	@ResponseBody
	public String nodeDel(Long nodeid) {

		menuService.del(nodeid);
		return "删除成功";
	}

}
